package com.sdk.springbootrediscache.multicache;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserService2 {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    @Qualifier("caffeineCacheManager")
    private CacheManager caffeineCacheManager;

    @Autowired
    @Qualifier("redisCacheManager")
    private CacheManager redisCacheManager;



    private Map<Long, String> userMap = new HashMap<>();

    // 从缓存中获取用户信息，如果缓存中不存在，则执行方法并将结果存入缓存
    //如果不设置cachemanager，就默认是caffeineCacheManager
    @Cacheable(value = "users", key = "#userId",cacheManager = "caffeineCacheManager")
    public String getUserById(Long userId) {
        System.out.println("Fetching user from database...");
        return userMap.get(userId);
    }

    // 更新用户信息，并更新缓存
    @CachePut(value = "users", key = "#userId",cacheManager ="redisCacheManager")
    public String updateUser(Long userId, String userName) {
        userMap.put(userId, userName);
        manualCache();
        return userName;
    }

    // 删除用户信息，并从缓存中移除
    @CacheEvict(value = "users", key = "#userId",cacheManager ="redisCacheManager")
    public void deleteUser(Long userId) {
        userMap.remove(userId);
    }

    public void manualCache(){
        //cacheManager默认是按@Primary注解标识的cachemanager查找users缓存，可以按下面的写法指定用caffine还是redis
        Objects.requireNonNull(cacheManager.getCache("users")).putIfAbsent(10L, "user10");
        Objects.requireNonNull(caffeineCacheManager.getCache("users")).putIfAbsent(10L, "user10");
        Objects.requireNonNull(redisCacheManager.getCache("users")).putIfAbsent(10L, "user10");

    }
}
